import React, { Component } from 'react';
import { connect } from 'dva';
import { Table, Modal, Input, Select } from 'antd';
// import moment from 'moment';
import styles from './Competior.less';
import mdf from 'react-native-md5';

const Option = Select.Option;

@connect(({ Competior }) => ({
  competiorData: Competior.competiorData,
  updateDidFinish: Competior.updateDidFinish,
}))
class Competior extends Component {
  state = {
    page_num: 1,
    page_size: 10,
    type: 0,
    CompetiorVisibility: false,
    CompanyID: '',
    CompetiorName: '',
    CompetiorType: 0,
    selectedRows: [],
  };

  updateData() {
    const { dispatch } = this.props;
    dispatch({
      type: 'Competior/queryorderList',
      payload: {
        page_num: this.state.page_num,
        page_size: this.state.page_size,
      },
    });
  }

  componentDidMount() {
    const { dispatch } = this.props;
    this.setState({ loading: false, CompetiorType: 0 });
    // let n = ['0', '093a66e4a1860d05b0758cc99a7c138f', '3cbae1d09998894bcfa20a576f1f3329', 'b59d0794a9534fe40c1ed80c8ab70b94', 'web', '平安保险']
    // console.log("排序后:",n.sort().toString().replace(/,/g, '&'))
    // console.log("编译字符串:",encodeURIComponent(n.sort().toString().replace(/,/g, '&')))
    // let md = encodeURIComponent(n.sort().toString().replace(/,/g, '&'))
    // console.log("加密结果:",mdf.hex_hmac_md5(JSON.parse(sessionStorage.getItem('LOGIN_INFO')).sign,md))
    this.updateData();
    // dispatch({
    //   type: 'AffiliatedCompany/getOrderList',
    //   payload: {
    //     page_num: 1,
    //     page_size: 10,
    //   },
    // });
  }

  componentDidUpdate(prevProps) {
    if (prevProps.updateDidFinish !== this.props.updateDidFinish) {
      this.updateData();
    } else if (prevProps.smtpList !== this.props.smtpList) {
      this.setState({ selectedRows: [] });
    }
  }

  render() {
    let { competiorData } = this.props;
    // console.log('competiorData', competiorData);
    const selectedRows = [
      {
        name: '主营业务',
        product_type_id: 0,
      },
      {
        name: '其他业务',
        product_type_id: 1,
      },
    ];
    const cols = [
      {
        title: '公司名称',
        dataIndex: 'company_name',
        key: 'competior_name',
      },
      {
        title: '业务分类',
        dataIndex: 'business_type_name',
        key: 'business_type_name',
      },
      {
        title: '操作',
        key: 'operations',
        dataIndex: 'id',
        render: (text, row, index) => (
          <a
            onClick={() => {
              handleEditClick(index);
            }}
          >
            编辑
          </a>
        ),
      },
    ];

    let pager = {
      defaultCurrent: 1,
      total: competiorData.total_count,
      onChange: (page, pageSize) => {
        this.setState({ page_num: page }, () => {
          this.updateData();
          this.setState({ selectedRows: [] });
        });
      },
    };

    let handleEditClick = index => {
      // console.log(competiorData.data_list)
      this.setState({
        CompanyID: competiorData.data_list[index].id,
        CompetiorName: competiorData.data_list[index].company_name,
        CompetiorType: competiorData.data_list[index].business_type_id,
        CompetiorVisibility: true,
        modalOperation: 'update',
      });
    };

    let handleDeleteClick = () => {
      const { dispatch } = this.props;

      if (this.state.selectedRows.length > 0) {
        const { dispatch } = this.props;
        let res = [];
        for (let i = 0; i < this.state.selectedRows.length; i++) {
          res.push(competiorData.data_list[this.state.selectedRows[i]].id);
        }
        // console.log("res ===",res.sort().toString().replace(/,/g, ','))
        dispatch({
          type: 'Competior/deleteCompetior',
          payload: {
            id: res
              .sort()
              .toString()
              .replace(/,/g, '-'),
          },
        });
      }
    };

    let handleTableSelectChange = selectedRows => {
      // console.log("selectedRows",selectedRows.sort().toString().replace(/,/g, ','));
      this.setState({ selectedRows });
    };

    let clearModalValues = () => {
      this.setState({
        CompetiorName: '',
        CompetiorType: 0,
        CompetiorVisibility: false,
      });
    };

    let handleModalOk = e => {
      const { dispatch } = this.props;
      if (this.state.modalOperation === 'new') {
        dispatch({
          type: 'Competior/addCompetior',
          payload: {
            company_name: this.state.CompetiorName,
            business_type_id: String(this.state.CompetiorType),
          },
        });
      } else {
        // console.log("updata",this.state.CompetiorType)
        dispatch({
          type: 'Competior/updateCompetior',
          payload: {
            id: this.state.CompanyID,
            company_name: this.state.CompetiorName,
            business_type_id: String(this.state.CompetiorType),
          },
        });
      }
      clearModalValues();
    };

    let handleModalCancel = e => {
      clearModalValues();
    };

    let handleInputChange = value => {
      console.log(value);
      this.setState(value);
    };

    let generateUserList = () => {
      let res = [];
      if (selectedRows) {
        for (let i = 0; i < selectedRows.length; i++) {
          res.push(
            <Option value={selectedRows[i].product_type_id} key={'user' + i}>
              {selectedRows[i].name}
            </Option>
          );
        }
      }
      return res;
    };

    return (
      <div style={{ margin: '24px 24px 0' }}>
        <div className={styles.outerWidthLim}>
          <div className={styles.outerHeightLim}>
            <div className={styles.contentCard}>
              <div className={styles.cardHeader}>
                <p className={styles.cardTitle}>竞争对手设置</p>
                <div className={styles.operationBox}>
                  <a
                    onClick={() => {
                      this.setState({ CompetiorVisibility: true, modalOperation: 'new' });
                    }}
                  >
                    添加
                  </a>
                  <span className={styles.smallGap}>|</span>
                  <a onClick={handleDeleteClick}>删除</a>
                </div>
              </div>
              <div className={styles.cardContent}>
                <Table
                  className={styles.bigTable}
                  columns={cols}
                  rowSelection={{
                    selectedRowKeys: this.state.selectedRows,
                    onChange: handleTableSelectChange,
                  }}
                  dataSource={competiorData.data_list}
                  pagination={pager}
                />
              </div>
            </div>
          </div>
        </div>

        <Modal
          title="添加竞争对手"
          okText="保存"
          visible={this.state.CompetiorVisibility}
          onOk={handleModalOk}
          onCancel={handleModalCancel}
        >
          <div style={{ marginTop: '20px' }}>
            <span style={{ color: 'red' }}>*</span>
            <span className={styles.SelectTitle}>公司名称：</span>
            <Input
              onChange={value => handleInputChange({ CompetiorName: value.target.value })}
              value={this.state.CompetiorName}
              style={{ width: '75%', float: 'right' }}
            />
          </div>
          <div style={{ marginTop: '20px' }}>
            <span style={{ color: 'red' }}>*</span>
            <span className={styles.SelectTitle}>业务分类：</span>
            <Select
              // mode="multiple"
              onChange={value => handleInputChange({ CompetiorType: value })}
              value={this.state.CompetiorType}
              style={{ width: '75%', float: 'right' }}
            >
              {generateUserList()}
            </Select>
          </div>
        </Modal>
      </div>
    );
  }
}

export default Competior;
